package com.fingard.dsp.bank.directbank.cqsx01;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;

/**
 * Created by F on 2017/6/20.
 */
public class CQSX01Transaction extends CQSX01Base implements ITransaction {

    //采用流处理方式
    //1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用writeRetDetail()，写入返回ATS的明细
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        String bodycontent = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            StringBuilder reqXml = new StringBuilder();
            reqXml.append(String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Message> <Head> <TrsCode>B2EActTrsQry</TrsCode> <ERPTrsTimestamp>%s</ERPTrsTimestamp></Head> <Body> <List>",
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
            reqXml.append(String.format("<Map><AcNo>%s</AcNo><Currency>%s</Currency><BeginDate>%s</BeginDate><EndDate>%s</EndDate></Map>",
                    p_req7516.actNum, super.convertCurToBank(p_req7516.actCur), new SimpleDateFormat("yyyy-MM-dd").format(p_req7516.getDateFrom()),
                    new SimpleDateFormat("yyyy-MM-dd").format(p_req7516.getDateTo())));
            reqXml.append("</List> </Body> </Message>");
            String[] tmpStrRet = sendToBank(reqXml.toString(), "B2EActTrsQry");
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String returnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if (isActiveRetCode(returnCode)) {
                        int tmpEachPiCount = 0;
                        while (tmpBkReader.read("/Message/Body/List/Map")) {
                            tmpEachPiCount++;
                            String accountNum = tmpBkReader.readedXElement.getSingleText("AcNo");
                            List<XElement> xElementList=tmpBkReader.readedXElement.getSingleChild("List").getChildList("Map");
                            for(XElement xElement:xElementList){
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.actNum = accountNum;
                                tmpRetDetail.cur=convertCurToATS(xElement.getSingleText("Currency"));
                                if(StringHelper.isNullOrEmpty(tmpRetDetail.cur)){
                                    tmpRetDetail.cur=p_req7516.actCur;
                                }
                                tmpRetDetail.accBal = xElement.getSingleText("Balance");
                                tmpRetDetail.recAccNum = xElement.getSingleText("PartnerAcct");
                                tmpRetDetail.recAccName = xElement.getSingleText("PartnerAcName");
                                String creditDebitFlag = xElement.getSingleText("DCFlag");//＋，表示存入；－，表示借出 D:借 C：贷
                                String tranAmount = xElement.getSingleText("Amount");
                                if (creditDebitFlag != null) {
                                    if ("D".equals(creditDebitFlag)) //表示支出
                                    {
                                        if (tranAmount.startsWith("-")) {
                                            tmpRetDetail.cdFlag = "2";
                                            tmpRetDetail.tranAmt=tranAmount.substring(1);
                                        } else {
                                            tmpRetDetail.cdFlag = "1";
                                            tmpRetDetail.tranAmt=tranAmount;
                                        }
                                    } else if ("C".equals(creditDebitFlag)) {
                                        if (tranAmount.startsWith("-")) {
                                            tmpRetDetail.cdFlag = "1";
                                            tmpRetDetail.tranAmt=tranAmount.substring(1);
                                        } else {
                                            tmpRetDetail.cdFlag = "2";
                                            tmpRetDetail.tranAmt=tranAmount;
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "返回的借贷标志未知";
                                        retAts = new RetAtsTrans(p_req7516.reqHeader);
                                        retAts.writeStart();//写返回ATS的统一头部信息
                                        retAts.writeRespCode(tmpRespCode);
                                        retAts.writeRespInfo(tmpRespInfo);
                                        retAts.writeEnd();
                                        return retAts;
                                    }
                                }
                                //tmpRetDetail.tranAmt = tranAmount.replace("-", "");
                                String tranTime = xElement.getSingleText("TransTime");
                                tmpRetDetail.tranDate = xElement.getSingleText("TransDate");
                                if(tranTime.length()==6){
                                    tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime.substring(0, 2) + ":" + tranTime.substring(2, 4) + ":" + tranTime.substring(4, 6);
                                }else {
                                    tmpRetDetail.tranTime = tmpRetDetail.tranDate+" 00:00:00";
                                }
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日没有返回就用交易日

                                tmpRetDetail.usage = xElement.getSingleText("Remark");
                                tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
                                    tmpRetDetail.actNum = p_req7516.actNum;
                                }
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        }

                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = returnMsg;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = "读取报文出错";
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "无法连接银行";
            }

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用b2e0035
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }


}
